<template>
  <div class="excelBody">
    <el-alert
      v-if="showInfo"
      :title="`有${erro_num}条错误信息，请校验，如无错误可忽略，共${excelList.length}条数据`"
      type="warning"
      show-icon>
    </el-alert>
    <div class="excelBody-upload" v-if="!showExcel">
      <el-upload
        class="upload-demo"
        drag
        :on-change="handleBeforeUpload"
        action=""
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </div>
    <div class="excelBody-table" v-else>
      <div class="excelBody-table-tobody">
        <div class="excelBody-table-tobodyTh">
          <div class="excelBody-table-tobodyTh-th nameline">
            孩子姓名
          </div>
          <div class="excelBody-table-tobodyTh-th dis-fl">
            孩子身份证号
          </div>
          <div class="excelBody-table-tobodyTh-th sexline">
            性别
          </div>
          <div class="excelBody-table-tobodyTh-th nationline">
            民族
          </div>
          <div class="excelBody-table-tobodyTh-th dis-fl">
            户籍地址
          </div>
          <div class="excelBody-table-tobodyTh-th nameline">
            父母一姓名
          </div>
          <div class="excelBody-table-tobodyTh-th dis-fl">
            父母一证件号码
          </div>
          <div class="excelBody-table-tobodyTh-th parentsPhone-line">
            父母一联系电话
          </div>
          <div class="excelBody-table-tobodyTh-th nameline">
            父母二姓名
          </div>
          <div class="excelBody-table-tobodyTh-th dis-fl">
            父母二证件号码
          </div>
          <div class="excelBody-table-tobodyTh-th parentsPhone-line">
            父母二联系电话
          </div>
          <div class="excelBody-table-tobodyTh-th birth-line">
            出生日期
          </div>
          <div class="excelBody-table-tobodyTh-th twinsline">
            双胞胎编号
          </div>
        </div>
        <div class="excelBody-table-tobodyTd">
          <!--          errInputList-->
          <div class="excelBody-table-tobodyTh-tdList" v-for="(item,index) in excelList" :key="index"
               :class="{'errInputList': item.list_erro}">
            <div class="excelBody-table-tobodyTh-td nameline" :class="{'errInput':item.name_erro}">
              <el-input v-model="item.name" placeholder="孩子姓名" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td dis-fl" :class="{'errInput':item.card_erro}">
              <el-input v-model="item.identity_card" placeholder="孩子身份证号" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td sexline" :class="{'errInput':item.sex_erro}">
              <el-input v-model="item.sex" placeholder="性别" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td nationline">
              <el-input v-model="item.nation" placeholder="民族" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td dis-fl">
              <el-input v-model="item.census_register" placeholder="户籍地址" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td nameline">
              <el-input v-model="item.parent1.name" placeholder="父母一姓名" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td dis-fl">
              <el-input v-model="item.parent1.identity_card" placeholder="父母一证件号码" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td parentsPhone-line">
              <el-input v-model="item.parent1.mobile_phone" placeholder="父母一联系电话" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td nameline">
              <el-input v-model="item.parent2.name" placeholder="父母二姓名" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td dis-fl">
              <el-input v-model="item.parent2.identity_card" placeholder="父母二证件号码" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td parentsPhone-line">
              <el-input v-model="item.parent2.mobile_phone" placeholder="父母二联系电话" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td birth-line" :class="{'errInput':item.birthday_erro}">
              <el-input v-model="item.birthday" placeholder="出生日期" size="mini"></el-input>
            </div>
            <div class="excelBody-table-tobodyTh-td twinsline">
              <el-input v-model="item.twins" placeholder="双胞胎编号" size="mini"></el-input>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
var XLSX = require('xlsx')
// import {readFile} from './excelRreadFile.js'; //读取excel文件方法

export default {
  data() {
    return {
      allowed: [
        'xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'xls', "application/vnd.ms-excel",
        'csv', "text/csv"],
      loading: false,
      excelList: [],
      erro_num: 0,
      showExcel: false,
      showInfo:false
    }
  },
  created() {
  },
  methods: {
    testFn(dataOption) {
      let that = this
      let data_ = JSON.parse(JSON.stringify(dataOption[0].sheet))
      let list_ = []
      let num_ = 0 // 几组双胞胎
      let erro_num = 0
      for (let item of data_) {
        let newList = {}
        // 判断几个孩子
        if (item['孩子姓名']) {
          let child_list = item['孩子姓名']?item['孩子姓名'].split(','):''
          let sex_list = item['性别']?item['性别'].split(','):''
          let census_register_list = item['户籍地址']?item['户籍地址'].split(','):''
          let identity_card_list = item['孩子身份证号']?item['孩子身份证号'].split(','):''
          let nation_list = item['民族']?item['民族'].split(','):''
          if (child_list.length > 1) {
            num_ = num_ + 1
          }
          for (let index in child_list) {
            newList = {
              name: child_list[index] || '', // 孩子姓名
              sex: sex_list[index] || '', // 性别
              nation: nation_list[index] || '', // 民族
              identity_card: identity_card_list[index] || '', //身份证
              birthday: '',  // 出生
              twins: child_list.length > 1 ? num_ : '', // 双胞胎编号
              census_register: census_register_list[index] || '', // 户籍
              parent1: {
                name: item['父母一姓名'] || '', // 家长姓名
                identity_card: item['父母一证件号码'] || '', // 家长身份证
                mobile_phone: item['父母一联系电话'] || '' // 家长电话
              },
              parent2: {
                name: item['父母二姓名'] || '', // 家长姓名
                identity_card: item['父母二证件号码'] || '', // 家长身份证
                mobile_phone: item['父母二联系电话'] || '' // 家长电话
              }
            }
            //身份证截取生日
            let birthday_ = that.validID(identity_card_list[index])
            newList.birthday = !birthday_ ? '' : birthday_
            let status_num = false
            if (!birthday_) {
              newList.birthday_erro = true
              newList.list_erro = true
              status_num = true
            }
            if (!sex_list[index]) {
              newList.sex_erro = true
              newList.list_erro = true
              status_num = true
            }
            if (!identity_card_list[index]) {
              newList.card_erro = true
              newList.list_erro = true
              status_num = true
            }
            if (status_num) {
              erro_num = erro_num + 1
            }

            list_.push(newList)
          }
        } else {
          newList = {
            name: item['孩子姓名'], // 孩子姓名
            sex: item['性别'], // 性别
            nation: item['民族'] || '', // 民族
            identity_card: item['孩子身份证号'] || '', //身份证
            birthday: '',  // 出生
            twins: '', // 双胞胎编号
            census_register: item['户籍地址'] || '', // 户籍
            parent1: {
              name: item['父母一姓名'] || '', // 家长姓名
              identity_card: item['父母一证件号码'] || '', // 家长身份证
              mobile_phone: item['父母一联系电话'] || '' // 家长电话
            },
            parent2: {
              name: item['父母二姓名'] || '', // 家长姓名
              identity_card: item['父母二证件号码'] || '', // 家长身份证
              mobile_phone: item['父母二联系电话'] || '' // 家长电话
            }
          }
          //身份证截取生日
          let birthday_ = that.validID(item['孩子身份证号'])
          newList.birthday = !birthday_ ? '' : birthday_
          if (!birthday_) {
            newList.birthday_erro = true
            newList.list_erro = true
          }
          if (!item['性别']) {
            newList.sex_erro = true
            newList.list_erro = true
          }
          if (!item['孩子身份证号']) {
            newList.card_erro = true
            newList.list_erro = true
          }
          newList.name_erro = true
          newList.list_erro = true
          erro_num = erro_num + 1
          list_.push(newList)
        }
      }
      this.erro_num = erro_num
      this.excelList = list_
      this.showInfo = true
      this.showExcel = true
    },
    clearfn(){
      this.showExcel = false
      this.excelList  = []
    },
    // 实现自动生成生日，性别，年龄
    validID(value) {
      // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (reg.test(value)) {
        let birth = null;
        if (value.length === 18) {
          birth = value.substring(6, 14);
        }
        if (value.length === 15) {
          birth = "19" + value.substring(6, 12);
        }
        return birth
      } else {
        return false
      }
    },
    async handleBeforeUpload(file) {
      //选择文件后
      let _this = this

      _this.showLoading(true)

      //检测文件类型
      if (!_this.checkFileType(file)) {
        console.log('抱歉，请选择excel文件')

        _this.showLoading(false)
        return false
      }

      //选择excel文件后，并读取其内容（文件流）
      let dataBinary = await this.analysis(file)
      console.log('识别出来的数据', dataBinary)
      if (dataBinary != null) {
        this.testFn(dataBinary)
      }
    },
    //解析excel
    analysis(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        reader.onload = function (e) {
          const data = e.target.result;
          this.wb = XLSX.read(data, {
            type: "binary"
          });
          const result = [];
          this.wb.SheetNames.forEach(sheetName => {
            console.log(sheetName)
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            });
          });
          resolve(result);
        };
        reader.readAsBinaryString(file.raw);
        // reader.readAsBinaryString(file) // 传统input方法
      });
    },
    showLoading(val) {
      let _this = this
      _this.loading = val
    },
    checkFileType(file) {
      let _this = this

      let flog = false

      //得到上传文件的值
      let fileName = file.name

      //取其类型
      let fileType = fileName.lastIndexOf('.')

      //返回位于String对象中指定位置的子字符串并转换为小写.
      let extension = fileName
        .substring(fileType)
        .toLowerCase()
        .replace('.', '')
      //判断允许上传的文件格式
      if (_this.allowed.includes(extension)) {
        flog = true
      } else {
        flog = false
      }

      return flog
    },
    sendData() {
      let n = this
      let excelList_ = JSON.parse(JSON.stringify(this.excelList))
      let status = true
      if(!this.excelList.length){
        this.$message.error('请导入需要分班的学生信息')
        return
      }
      for (let index in excelList_) {
        if (!excelList_[index].name) {
          excelList_[index].name_erro = true
          excelList_[index].list_erro = true
        } else {
          excelList_[index].name_erro = false
          excelList_[index].list_erro = false
        }
        if (!excelList_[index].sex) {
          excelList_[index].sex_erro = true
          excelList_[index].list_erro = true
        } else {
          excelList_[index].sex_erro = false
          excelList_[index].list_erro = false
        }
        if (!excelList_[index].identity_card) {
          excelList_[index].card_erro = true
          excelList_[index].list_erro = true
        } else {
          excelList_[index].card_erro = false
          excelList_[index].list_erro = false
        }

        if (excelList_[index].birthday) {
          if (excelList_[index].birthday.length !== 8) {
            status = false
            excelList_[index].birthday_erro = true
            excelList_[index].list_erro = true
          } else {
            excelList_[index].birthday_erro = false
            excelList_[index].list_erro = false
          }
        } else {
          status = false
          excelList_[index].birthday_erro = true
          excelList_[index].list_erro = true
        }
        n.$set(n.excelList, index, excelList_[index])
      }
      if (status) {
        console.log('过了', excelList_)
        this.$emit('changeData', n.excelList)
        // window.parent.postMessage({
        //   data: {
        //     code: "success",
        //     data: n.excelList
        //   }
        // }, '*');
      } else {
        this.$message.error('请正确填写必要信息')
      }
    }
  },
  mounted() {
    // let n = this;
    // window.addEventListener('message', function (e) {
    //   console.log('来自父元素的数据')
    //   console.log(e.origin, e.data)
    //   if (e.data.type === 1) {
    //     // 开始上传图片了
    //     console.log('发送本页数据')
    //     n.sendData()
    //   }
    // })
  }
}
</script>

<style scoped>
.excelBody {
  height: 100%;
  width: 100%;
}

.excelBody-upload {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.excelBody-table-tobody {
  display: flex;
  flex-direction: column;
  background: #fff;
  border: 1px solid #f4f4f9;
}

.excelBody-table-tobodyTh {
  height: 40px;
  width: 100%;
  display: flex;
  align-items: center;
}

.excelBody-table-tobodyTh-th {
  border-right: 1px solid #f4f4f9;
  background: #d4edff;
  text-align: center;
  height: 40px;
  line-height: 40px;
  font-size: 12px;
  font-weight: bold;
  box-sizing: border-box;
}

.excelBody-table-tobodyTd {
  flex: 1;
  overflow-y: auto;

}

.excelBody-table-tobodyTh-tdList {
  display: flex;
  border-bottom: 1px solid #f4f4f9;
}

.excelBody-table-tobodyTh-td {
  padding: 5px 2px;
  box-sizing: border-box;
}

.sexline {
  width: 60px;
}
.nationline{
  width: 70px;
}
.nameline{
  width: 80px;
}
.twinsline{
  width: 70px;
}
.birth-line{
  width: 90px;
}
.parentsPhone-line{
  width: 115px;
}
.errInputList {
  background: #FBA4AD3D;
}
.dis-fl{
  flex: 1;
}
</style>
